layui.use(['element', 'table', 'tree', 'zlpoptree', 'zltreemenu', 'zlContext', 'zlConfig', 'treeGrid', 'zlPopSourceForm', 'zlPinYin', 'zlSelectEx'], function (exports) {
    var $ = layui.$,
        zlContext = layui.zlContext,
        zltreemenu = layui.zltreemenu,
        layer = layui.layer,
        zlConfig = layui.zlConfig,
        zlPopSourceForm = layui.zlPopSourceForm,
        zlpoptree = layui.zlpoptree,
        statusName = zlConfig.global.result.statusName,
        msgName = zlConfig.global.result.msgName,
        OK = zlConfig.global.result.okState,
        form = layui.form,
        treeGrid = layui.treeGrid,
        zlPinYin = layui.zlPinYin,
        tableId = 'treeTable',
        fullheight = zlContext.setMaxHeihgt(0);

    var frm = [
        '<form class="layui-form " style="margin:8px" id="addnew" >'
        , '   <input type="hidden" name="ORGID">'
        , '   <input type="hidden" name="SELORGID">'
        , '   <input type="hidden" name="RWID">'
        , '   <input type="hidden" name="type">'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12 ">'
        , '           <label class="layui-form-label">名称</label>'
        , '           <div class="layui-input-block">'
        , '                 <input type="text" class="layui-input" lay-filter="OBJNAME" name="OBJNAME" maxlength="40" lay-verify="required">'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12 ">'
        , '           <label class="layui-form-label">编号</label>'
        , '           <div class="layui-input-block">'
        , '               <input type="text" class="layui-input" lay-filter="OBJCODE" name="OBJCODE" maxlength="50" lay-verify="required">'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12 ">'
        , '           <label class="layui-form-label">菜单类型</label>'
        , '           <div class="layui-input-block">'
        , '		            <select name="RES_TYPE" lay-filter="RES_TYPE"  lay-verify="required"  placeholder="请选择菜单类型" zlcomponent class="select-ext" settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querymenudictionary' + '\'}">'
        , '		            </select>'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">图标</label>'
        , '           <div class="layui-input-block" id="smalldiv">'
        , '               <div name="ICON_SMALL" zlcomponent class="layui-form-select zlPopSourceForm">'
        , '               </div>'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">关联的功能</label>'
        , '           <div class="layui-input-block">'
        , '               <div name="RELE_RES_ID" zlcomponent class="layui-form-select zlpoptree" text="" value="">'
        , '               </div>'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">排序</label>'
        , '           <div class="layui-input-block">'
        , '               <input type="text" class="layui-input" lay-verify="required|number" lay-filter="SYS_SORT" maxlength="5" name="SYS_SORT">'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '        <div class="layui-col-md12">'
        , '             <label name="pfunction" class="layui-form-label">上级菜单</label>'
        , '             <div class="layui-input-block">'
        , '                  <div name="SYS_PARENTID" zlcomponent class="layui-form-select zlpoptree" text="" value="">'
        , '                   </div>'
        , '             </div>'
        , '         </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-col-md12">'
        , '           <label class="layui-form-label">备注</label>'
        , '           <div class="layui-input-block">'
        , '               <textarea class="layui-textarea" lay-filter="BEIZ" maxlength="40" name="BEIZ"></textarea>'
        , '           </div>'
        , '       </div>'
        , '   </div>'
        , '   <div class="layui-form-item">'
        , '       <div class="layui-input-block">'
        , '           <button class="layui-btn"  id="btnadd" lay-submit  lay-filter="addfunction">保存</button>'
        , '       </div>'
        , '   </div>'
        , '</form>'
    ],
        formindex,
        totalcount,
        isloadsearch = false,
        newFormObj = {};

    var orgtreeObj = zltreemenu.render('orgtree', {
        dataurl: layui.cache['contentPath'] + "/manager/corefunction/queryorgddata",
        type: "get",
        tableId: tableId,
        isMove: false
    }, {
            onAsyncSuccess: function (event, treeId, treeNode, msg) {
                orgtreeObj.selectNode(orgtreeObj.getNodes()[0]);
                $('#' + orgtreeObj.getNodes()[0].tId + '_a').click()
            },
            onClick: function (event, treeId, treeNode) {
                var loadingLayer = layer.msg('数据查询中，请稍候...', {
                    icon: 16,
                    time: false,
                    shade: 0.1
                });
                $('input[name="ORGIDTEMP"]').val(treeNode.RWID);
                treeGrid.reload('treeTable', {
                    url: layui.cache['contentPath'] + '/manager/coremenu/query?orgid=' + $('input[name="ORGIDTEMP"]').val(),
                    height: fullheight,
                    method:'POST',
                    done: function (res, curr, count) {
                        layer.close(loadingLayer);
                        if (res.obj.length == 0) {
                            totalcount = 0
                        } else {
                            var data = res.obj;
                            totalcount = data[0].SYS_SORT;
                            for (var i = 0; i < data.length; i++) {
                                if (totalcount < data[i].SYS_SORT) {
                                    totalcount = data[i].SYS_SORT;
                                }
                            }
                        }
                    }
                });
            }
        })
    var  restype = {
        'EB7113E02DA643D3B800A03ED2D87C09': '隐藏菜单'
        , 'D0F4A751E3654AB3A714B8A0309D0BCB': '菜单'
        , '4C5CE7CCD7124C448A82E65B965B36CC': '菜单目录'
    }
    treeGrid.render({
        id: tableId,
        elem: '#' + tableId,
        method: 'get',
        cellMinWidth: 100,
        treeId: 'RWID', //树形id字段名称
        treeUpId: 'SYS_PARENTID', //树形父id字段名称
        treeShowName: 'OBJNAME', //以树形式显示的字段
        limit: 1000,
        height: fullheight,
        isOpenDefault: false,
        //, branch: ['&#xe622;', '&#xe630;'] //父节点
        chkboxType: {
            "Y": "",
            "N": ""
        }, //父子节点的关联关系 默认值：{ "Y": "ps", "N": "ps" }
        cols: [
            [{
                type: 'checkbox'
            }, {
                field: 'OBJNAME',
                width: '200',
                title: '名称',
                sort: true
            }, {
                field: 'OBJCODE',
                width: '100',
                title: '编号',
                sort: true
            }, {
				field: 'RES_TYPE', width: '90', title: '菜单类型', templet: function (d) {
					return '<span>' + restype[d.RES_TYPE] + '</span>'
                }
            },{
                field: 'ICON_SMALL',
                width: '100',
                title: '图标',
                templet: function (d) {
                    if (d.ICON_SMALL_URL == "") {
                        return ''
                    } else {
                        return '<img atl="" src="' + layui.cache['contentPath'] + d.ICON_SMALL_URL + '">'
                    }
                }
            }, {
                field: 'RESNAME',
                width: '250',
                title: '关联的功能名'
            }, {
                field: 'SYS_SORT',
                width: '150',
                title: '排序',
                sort: true
            }, {
                field: 'BEIZ',
                width: '200',
                title: '备注'
            }]
        ],
        isPage: false,
        response: zlConfig.global.gridResponse,
        done: function (res, curr, count) {
            //layer.close(loadingLayer)
            if (res.obj.length == 0) {
                totalcount = 0
            } else {
                var data = res.obj;
                totalcount = data[0].SYS_SORT;
                for (var i = 0; i < data.length; i++) {
                    if (totalcount < data[i].SYS_SORT) {
                        totalcount = data[i].SYS_SORT;
                    }
                }
            }
        }
    });

    var iconsetting = "{shiycjid:'E1582A0455AD4DF9A2C2E77D58E13F22',isOpenAdQ:true,edittype:'readonly',type:'image'," +
        'coltitle:[[' +
        '{ type: "numbers", fixed: "left", title: "#" },' +
        '{ type: "radio", fixed: "left" },' +
        '{ field: "WJZY_MINGC", title: "名称", width: 100 },' +
        '{ field: "WJZY_BIANH", title: "编号", width: 150 },' +
        '{ field: "WJZY_ZIYLJ", title:"资源", width: 150,templet: "<div><img atl=' + "''" + "src='" + layui.cache['contentPath'] + "{{ d.WJZY_ZIYLJ}}" + "'" + '></div>"}]],' +
        "limit:10,formtitle:'选择图标', placeholder:'请选择图标',page:true, id:'RWID',name : 'WJZY_ZIYLJ', method:'post',params:'{WJZY_LEIX:0}' ,dataurl:'" + layui.cache['contentPath'] + "/manager/corefilesres/query'}";
    var settings = "{dataurl:layui.cache['contentPath'] + '/manager/corefunction/query',method:'post',formtitle:'选择功能',placeholder:'请选择功能'}";
    var psettings = "{dataurl:layui.cache['contentPath'] + '/manager/coremenu/query?orgid=" + $('input[name="ORGIDTEMP"]').val() + "',method:'post',formtitle:'选择上级菜单',edittype:'readonly'}";
    // 展开或折叠全部
    $('#btnopenall').on('click', function () {
        var treedata = treeGrid.getDataTreeList('treeTable');
        if ($(this).find('i').hasClass("layui-icon-down")) {
            $(this).find('i').removeClass("layui-icon-down").addClass("layui-icon-up");
            $(this).find('span').text("收起全部")
        } else {
            $(this).find('i').removeClass("layui-icon-up").addClass("layui-icon-down");
            $(this).find('span').text("展开全部");
        }
        treeGrid.treeOpenAll('treeTable', !treedata[0][treeGrid.config.cols.isOpen]);
    });

    $('#btnnew').on('click', function () {
        var showform = frm.join('');
        var checkStatus = treeGrid.checkStatus('treeTable'),
            rows = checkStatus.data;
        if (rows.length > 1) {
            zlContext.errorMsg("不能同时在两个菜单下增加菜单！");
            return;
        }
        formindex = layer.open({
            type: 1,
            content: showform,
            title: "新增菜单",
            id: 'addMenuLayer',
            area: ['100%', '100%'],
            success: function (index) {
                iconsetting = iconsetting.replace(/readonly/gi, 'edit');
                psettings = psettings.replace(/readonly/gi, 'edit');
                $('input[name="OBJNAME"]').val('');
                $('input[name="OBJCODE"]').val('');
                $('input[name="RWID"]').val('');
                $('textarea[name="BEIZ"]').val('');
                $('input[name="type"]').val('add');
                $('#addnew div[name="SYS_PARENTID"]').attr("settings", psettings);
                if (rows.length > 0) {
                    $('#addnew div[name="SYS_PARENTID"]').attr("value", rows[0].RWID);
                    $('#addnew div[name="SYS_PARENTID"]').attr("text", rows[0].OBJNAME);
                }

                $('input[name="SELORGID"]').val($('input[name="ORGIDTEMP"]').val());
                $('div[name="RELE_RES_ID"]').attr('settings', settings);
                $('div[name="ICON_SMALL"]').attr('settings', iconsetting);
                $('input[name="SYS_SORT"]').val(totalcount + 1);
                addverify();
                ObjnameChange();
                form.render();
                if ($('input[name="RES_TYPE"]').val() == "D0F4A751E3654AB3A714B8A0309D0BCB") {
                    $('input[name="RELE_RES_NAME"]').attr('lay-verify', 'required');
                } else {
                    $('input[name="RELE_RES_NAME"]').attr('lay-verify', '');
                }

                if (zlContext.browserType() == 'IE') {
                    zlpoptree.render($('div[name=RELE_RES_ID]'));
                    zlPopSourceForm.render($('div[name=ICON_SMALL]'));
                }
            }
        });
    });

    $('#btndel').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeTable'),
            rows = checkStatus.data;
        if (rows.length == 0) {
            zlContext.warnMsg("请选择需要删除的菜单");
            return;
        }
        var id = new Array(),
            orgid = new Array(),
            objname = new Array(),
            canpost = true;
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].children.length > 0) {
                zlContext.warnMsg(rows[i].OBJNAME + "菜单节点下还有菜单，请先删除子菜单");
                canpost = false;
                return;
            }
            id.push(rows[i].RWID);
            objname.push(rows[i].OBJNAME);
            orgid.push(rows[i].ORGID);
        }
        if (!canpost) {
            return;
        }

        zlContext.confirm('询问', '是否要删除选择的菜单吗？', function (index) {
            //删除对应行（tr）的DOM结构
            //向服务端发送删除指令
            var param = {
                RWID: id.join(),
                SELORGID: $('input[name="ORGIDTEMP"]').val(),
                ORGID: orgid.join(),
                OBJNAME: objname.join(),
            };
            zlContext.deletePost(
                layui.cache['contentPath'] + '/manager/coremenu/del',
                param,
                function (data) {
                    if (data[statusName] == OK) {
                        treeGrid.reload('treeTable', {
                            url: layui.cache['contentPath'] + '/manager/coremenu/query?orgid=' + $('input[name="ORGIDTEMP"]').val(),
                            method:'POST',
                            height: fullheight
                            
                        });

                        zlContext.successMsg('删除成功');
                    } else {
                        zlContext.errorMsg(data[msgName]);
                    }
                })
            layer.close(index);
        });
    });

    $('#btnedit').on('click', function () {
        var checkStatus = treeGrid.checkStatus('treeTable'),
            rows = checkStatus.data;
        if (rows.length == 0) {
            zlContext.warnMsg("请选择需要修改的菜单节点！");
            return;
        } else if (rows.length > 1) {
            zlContext.warnMsg("每次只能勾选一个功能节修改！");
            return;
        }
        formindex = layer.open({
            type: 1,
            content: frm.join(''),
            title: "编辑菜单",
            id: 'editMenuLayer',
            area: ['100%', '100%'],
            success: function () {
                var orgid = $('input[name="ORGIDTEMP"]').val(),
                    data = rows[0];
                if (!(orgid == "" || orgid == "9C876276D8884BFF94DF343E2A4EED7D") && data.ORGID != orgid) {
                    $('select[name="RES_TYPE"]').attr('disabled', "disabled");
                    $('textarea[name="BEIZ"]').attr('disabled', "disabled");
                    $('textarea[name="BEIZ"]').addClass('layui-disabled');
                    psettings = psettings.replace(/edittype:'edit'/gi, "edittype:'readonly'");
                    iconsetting = iconsetting.replace(/edittype:'edit'/gi, "edittype:'readonly'");
                } else {
                    addverify();
                    psettings = psettings.replace(/edittype:'readonly'/gi, "edittype:'edit'");
                    iconsetting = iconsetting.replace(/edittype:'readonly'/gi, "edittype:'edit'");
                }
                if (data.ICON_SMALL != "") {
                    $('div[name="ICON_SMALL"]').attr('value', data.ICON_SMALL);
                    $('div[name="ICON_SMALL"]').attr('text', layui.cache['contentPath'] + data.ICON_SMALL_URL);
                };
                ObjnameChange();
                $('div[name="ICON_SMALL"]').attr('settings', iconsetting);
                $('div[name="RELE_RES_ID"]').attr('settings', settings);
                $('div[name="RELE_RES_ID"]').attr('value', data.RELE_RES_ID);
                $('div[name="RELE_RES_ID"]').attr('text', data.RESNAME);
                $('input[name="OBJNAME"]').val(data.OBJNAME);
                $('input[name="OBJCODE"]').val(data.OBJCODE);
                $('input[name="ICON_SMALL"]').val(data.ICON_SMALL);
                $('input[name="ICON_BIG"]').val(data.ICON_BIG);
                $('input[name="RWID"]').val(data.RWID);
                $('input[name="VISIBILITY"]').val(data.VISIBILITY);
                $('input[name="SYS_SORT"]').val(data.SYS_SORT);
                $('textarea[name="BEIZ"]').val(data.BEIZ);
                $('input[name="type"]').val('edit');
                $('input[name="SELORGID"]').val($('input[name="ORGIDTEMP"]').val());
                $('input[name="ORGID"]').val(data.ORGID);
                $('input[name="RELE_RES_NAME"]').val(data.RESNAME);
                $('#addnew input[name="SYS_PARENTS"]').val(data.SYS_PARENTS);
                $('#addnew div[name="SYS_PARENTID"]').attr("value", data.SYS_PARENTID);
                $('#addnew div[name="SYS_PARENTID"]').attr("settings", psettings);
                if (data.RES_TYPE == "D0F4A751E3654AB3A714B8A0309D0BCB") {
                    $('div[name="RELE_RES_ID"]').attr('verify', 'required');
                } else {
                    $('div[name="RELE_RES_ID"]').attr('verify', '');
                }
                //让下拉框显示出来
                form.render('');
                $('select[name="RES_TYPE"]').attr('value', data.RES_TYPE);
                form.render('select');
            },
            cancel: function (index, layero) {
                newFormObj.newFields = null;
                if ($('#addnew').find('.getField').length == 0) {
                    $('#addnew').append('<button class="layui-btn layui-hide getField" lay-submit lay-filter="addfunction">获取表单值</button>');
                }
                var verifyItem = $('#addnew').find('[lay-verify]');
                for (var i = 0; i < verifyItem.length; i++) {
                    var verifyStr = $(verifyItem[i]).attr('lay-verify');
                    if (verifyStr != '') {
                        $(verifyItem[i]).attr({
                            'lay-verify': '',
                            'data-verifyflag': verifyStr
                        })
                    }
                }
                $('#addnew').find('.getField').trigger('click');
                if (newFormObj.newFields == null) {
                    return false;
                }
                rows[0]['SELORGID'] = $('input[name="ORGIDTEMP"]').val()
                if (!zlContext.isObjectValueEqual(newFormObj.newFields, rows[0])) {
                    var changeConfirmLayer = layer.confirm('数据已有改动，是否要保存？', {
                        title: '是否关闭',
                        resize: false,
                        btn: ['保存关闭', '确定关闭', '取消'], //按钮
                        btnAlign: 'c',
                        anim: 1,
                        icon: 3
                    }, function () {
                        layer.close(changeConfirmLayer)
                        var items = $('#addnew').find('[data-verifyflag]')
                        for (var i = 0; i < items.length; i++) {
                            var verifyStr = $(items[i]).attr('data-verifyflag');
                            $(items[i]).attr({
                                'lay-verify': verifyStr,
                                'data-verifyflag': ''
                            });
                        }
                        $('#btnadd').trigger('click');
                        // obj.sumbit(obj.newFields);
                    }, function () {
                        layer.close(index)
                    }, function () {
                        layer.close(changeConfirmLayer)
                    });
                    return false;
                } else {
                    layer.close(index)
                }
            }
        });
    });

    form.on('submit(addfunction)', function (data) {
        if ($(data.elem).hasClass('getField')) {
            newFormObj.newFields = data.field
            return false;
        }
        // param = JSON.stringify(data.field);
        var type = $('input[name="type"]').val();
        var url = layui.cache['contentPath'] + "/manager/coremenu/add";
        if (type == "edit") {
            url = layui.cache['contentPath'] + "/manager/coremenu/modify";
            if (data.field.RWID == data.field.SYS_PARENTID) {
                zlContext.errorMsg('上级功能不能为自身');
                return false;
            }
        }
        zlContext.post(
            url,
            data.field,
            function (data) {
                if (data[statusName] == OK) {
                    layer.close(formindex);
                    treeGrid.reload('treeTable', {
                        url: layui.cache['contentPath'] + '/manager/coremenu/query?orgid=' + $('input[name="ORGIDTEMP"]').val(),
                        method:'POST',
                        height: fullheight
                    });
                    zlContext.successMsg('保存成功');
                } else {
                    zlContext.errorMsg(data[msgName]);
                }
            });
        return false;
    });

    function addverify() {
        form.on('select(RES_TYPE)', function (data) {
            var value = data.value;
            if (value == "D0F4A751E3654AB3A714B8A0309D0BCB") {
                $('input[name="inputRELE_RES_ID"]').attr('lay-verify', 'required');
            } else {
                $('input[name="inputRELE_RES_ID"]').attr('lay-verify', '');
            }
        });
    }

    function ObjnameChange() {
        $('input[name="OBJNAME"]').change(function () {
            var v = $('input[name="OBJNAME"]').val();
            $('input[name="OBJCODE"]').val(zlPinYin.C(v));
        });
    }

    $(window).on('resize', function () {
        zlContext.setMaxHeihgt(0);
    }).resize();
    
    $('#btnSeacher').on('click', function () {
        isloadsearch = true;
        var seachervalue = $('#edtSeacherValue').val();
        treeGrid.reload('treeTable', {
            url: layui.cache['contentPath'] + '/manager/coremenu/query?orgid=' + $('input[name="ORGIDTEMP"]').val(),
            method:'POST',
            height: fullheight,
            where :{
                searchvalue :seachervalue
            }

        });
    });

    $('#edtSeacherValue').on('keyup', function (event) {
		var keyCode = event.keyCode;
		if (keyCode == 13) {
			$('#btnSeacher').trigger('click');
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
			$('#btnSeacher').trigger('click');
			isloadsearch = false;
		}
	});

});
